//
//  WaterFallsLayout.m
//  WaterfallsFlowDemo
//
//  Created by CyanXu on 2022/3/5.
//

#import "WaterFallsLayout.h"
@interface WaterFallsLayout()
//@property(nonatomic,assign)CGFloat contentHeight;
@end


@implementation WaterFallsLayout
- (instancetype)init{
    self = [super init];
    if (self) {
        self.numberOfColumns = 2;
        self.minimumLineSpacing = 0;
        self.minimumInteritemSpacing = 0;
        self.contentHeight = 0;
        self.cache = [[NSMutableArray alloc] init];
    }
    return self;
}

- (CGSize)collectionViewContentSize{
//    NSLog(@"width:%.1f   contentHeight:%.1f",self.width,self.contentHeight);
    return CGSizeMake(self.width, self.contentHeight);
}
- (void)prepareLayout{
    if (self.cache.count == 0) {
        CGFloat columnWidth = (self.width - (self.numberOfColumns + 1)*self.minimumInteritemSpacing) / self.numberOfColumns;
        NSMutableArray *xOffsets = [NSMutableArray array];
        NSMutableArray *yOffsets = [[NSMutableArray alloc] init];
        for (int i = 0; i < self.numberOfColumns; i++) {
            CGFloat value = i*columnWidth + self.minimumInteritemSpacing*(i+1);
            [xOffsets addObject:@(value)];
            [yOffsets addObject:@(self.minimumLineSpacing)];
        }
    
        NSInteger column = 0;
        for (int item = 0; item < [self.collectionView numberOfItemsInSection:0]; item++) {
            NSIndexPath *indexPath = [NSIndexPath indexPathForItem:item inSection:0];
            CGFloat height = [self.delegate collectionView:self.collectionView heightForItemAtIndexPath:indexPath];
            CGRect frame = CGRectMake([xOffsets[column] floatValue], [yOffsets[column] floatValue], columnWidth, height);
            UICollectionViewLayoutAttributes *attributes = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];
            attributes.frame = frame;
//            NSLog(@"frame:%@",NSStringFromCGRect(frame));
            [self.cache addObject:attributes];
            self.contentHeight = MAX(self.contentHeight, CGRectGetMaxY(frame));
//            NSLog(@"contentHeight:%.f",self.contentHeight);
            yOffsets[column] = [NSNumber numberWithFloat:[yOffsets[column] floatValue] + height + self.minimumLineSpacing];
            column = column >= (self.numberOfColumns -1) ? 0 : column+1;
        }
    }
}

- (NSArray<__kindof UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect{
    NSMutableArray<UICollectionViewLayoutAttributes *> *layoutAttributes = [[NSMutableArray alloc] init];
    for (UICollectionViewLayoutAttributes *attributes in self.cache) {
        if (CGRectIntersectsRect(attributes.frame, rect)) {
            [layoutAttributes addObject:attributes];
        }
    }
    return layoutAttributes;
}

@end
